import platformApi from "./utils/platform";

/**
 * 设备测量功能模块
 * @param {Object} config - 配置项对象
 * @param {function} config.communicationData - 设备发送通信数据的生成函数
 * @param {function} config.errorHandler - 异常处理函数
 * @returns {Object} - 包含开始测量方法的对象
 */
export default function (config) {
  const { communicationData, errorHandler, serviceId } = config;
  let selectedDevice = null;
  let writeChar = null;
  let notifyChar = null;
  let measureData = null;

  /**
   * 设置设备信息
   * @param {Object} device - 设备对象
   * @param {Object} char - 特征值对象
   * @param {string} sId - 服务 ID
   */
  const setDeviceInfo = (_device, _writeChar, _notifyChar) => {
    selectedDevice = _device;
    writeChar = _writeChar;
    notifyChar = _notifyChar;
  };

  /**
   * 开始测量
   */
  const startMeasurement = () => {
    if (!selectedDevice || !writeChar || !notifyChar) {
      errorHandler(
        ErrorTypes.DEVICE_CONNECTION_FAILED,
        "设备未连接或特征值未获取",
        new Error("设备未连接或特征值未获取")
      );
      return;
    }

    const buffer = communicationData();
    platformApi.writeBLECharacteristicValue({
      deviceId: selectedDevice.deviceId,
      serviceId,
      characteristicId: writeChar.uuid,
      value: buffer,
      success: (res) => {
        console.log("发送指令成功", res);
        // 处理测量结果
        platformApi.onBLECharacteristicValueChange(handleDataReceived);
      },
      fail: (err) => {
        errorHandler(
          ErrorTypes.WRITE_DATA_FAILED,
          `发送数据失败: ${res.errMsg}`,
          res
        );
      },
    });
  };

  /**
   * 处理测量结果
   * @param {Object} res - 测量结果对象
   */
  const handleDataReceived = (res) => {
    console.log("测量结果", res);
    // 处理测量结果的逻辑
    measureData = res;
  };

  /**
   * 获取测量数据
   * @returns {Object} - 测量数据对象
   */
  const getMeasureData = () => {
    return measureData;
  };

  return { startMeasurement, setDeviceInfo, getMeasureData };
}
